﻿using System;
using System.Collections;
using System.IO;

namespace MichielWouters
{
    public partial class Add_cafe : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string selectedValue = ddlImagem.SelectedValue;
            ShowImagens();
            ddlImagem.SelectedValue = selectedValue;
        }
        private void ShowImagens()
        {
            //Get all filepaths
            string[] images = Directory.GetFiles(Server.MapPath("~/Imagens/Coffee"));

            //Get all filenames and add them to an arraylist
            ArrayList imageList = new ArrayList();

            foreach (string image in images)
            {
                string imageName = image.Substring(image.LastIndexOf(@"\") + 1);
                imageList.Add(imageName);
            }

            //Set the arrayList as the dropdownview's datasource and refresh
            ddlImagem.DataSource = imageList;
            ddlImagem.DataBind();
        }

        private void ClearTextFields()
        {
            txtName.Text = "";
            txtTipo.Text = "";
            txtRoast.Text = "";
            txtReview.Text = "";
            txtPreco.Text = "";
            txtPais.Text = "";
        }

        protected void btnUploadImagem_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/Imagens/Coffee/") + filename);
                lblResult.Text = "Image " + filename + " upload com sucesso!";
                Page_Load(sender, e);
            }
            catch (Exception)
            {
                
                lblResult.Text="Falha no upload!";
            }
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            try
            {                
                string name = txtName.Text;
                string type = txtTipo.Text;
                double price = Convert.ToDouble(txtPreco.Text);
                price = price/100;
                string roast = txtRoast.Text;
                string country = txtPais.Text;
                string image = "../Imagens/Coffee/" + ddlImagem.SelectedValue;
                string review = txtReview.Text;

                Cafe coff = new Cafe(name, type, price, roast, country, image, review);
                ConnectionClass.AddCoffee(coff);
                lblResult.Text = "Upload com sucesso";
                ClearTextFields();
            }
            catch (Exception)
            {
                lblResult.Text = "Falha ao salvar!";
            }
        }
    }
}